import React, { useEffect, useState } from 'react';
import { doNewProcess, getActiveTiList, doNewProcessByPdaid } from './dw-mx-sew/SEWEngine';
import { InitProcessVars, TaskInstance, DoNewProcessNoAuthData, DoNewProcessMultipleInstancesWarningData, DoNewProcessMultipleInstancesForbiddenData, DoNewProcessMultiplePDVersionsData, DoNewProcessSuccessData } from './dw-mx-sew/SEWEngineInterface';

import PIViewer from './PIViewer';
import PDVList from './PDVList';
import ActivePIList4Forbidden from './ActivePIList4Forbidden';
import ActivePIList4Warning from './ActivePIList4Warning';
import NoAuth from './NoAuth';
import store from './demo/redux/store';
import { Modal } from 'dw-mx';
import { GetUserInfoContext } from './GetUserInfoContext'

export interface PDViewerProps {
    pdid: string;
    userid: string;
    initProcessVars: InitProcessVars;
    ignoreWarning: boolean;
    ignoreAuth: boolean;
    onDestory: () => void;
    onTiChanged?: Function;
}
export interface Success {
    condition: 'Success';
    data: DoNewProcessSuccessData;
}
export interface NoAuth {
    condition: 'NoAuth';
    data: DoNewProcessNoAuthData;
}
export interface Warning {
    condition: 'Warning';
    data: DoNewProcessMultipleInstancesWarningData;
    from: {
        pdid?: string;
        pdaid?: string;
    };
}
export interface Forbidden {
    condition: 'Forbidden';
    data: DoNewProcessMultipleInstancesForbiddenData;
}
export interface PDVersions {
    condition: 'PDVersions';
    data: DoNewProcessMultiplePDVersionsData;
}
export interface Exception {
    condition: 'Error';
    data: string;
}

export default function PDViewer(props: PDViewerProps) {
    const { pdid, userid, initProcessVars, ignoreWarning = false, ignoreAuth = true, onDestory, onTiChanged } = props;
    const [state, updateState] = useState<Success | NoAuth | Warning | Forbidden | PDVersions | Exception>(null);
    useEffect(() => {
        onPdSelect(pdid, userid, initProcessVars, ignoreWarning, ignoreAuth);
    }, []);
    function onPdSelect(pdid: string, userid: string, initProcessVars: InitProcessVars, ignoreWarning: boolean, ignoreAuth: boolean) {
        store.dispatch({
            type: 'add',
            pditem: pdid,
        });
        doNewProcess(pdid, userid, initProcessVars, ignoreWarning, ignoreAuth)
            .then((newProcessResult) => {
                if (newProcessResult.result_code === '1') {
                    // 成功
                    updateState({
                        condition: 'Success',
                        data: {
                            piid: newProcessResult.result_message.piid,
                        },
                    });
                } else if (newProcessResult.result_code === '2') {
                    // 没权限
                    updateState({
                        condition: 'NoAuth',
                        data: newProcessResult.result_message,
                    });
                } else if (newProcessResult.result_code === '3') {
                    // 多实例警告
                    updateState({
                        condition: 'Warning',
                        data: newProcessResult.result_message,
                        from: {
                            pdid,
                        },
                    });
                } else if (newProcessResult.result_code === '4') {
                    // 多实例禁止
                    updateState({
                        condition: 'Forbidden',
                        data: newProcessResult.result_message,
                    });
                } else if (newProcessResult.result_code === '6') {
                    // 多流程版本
                    updateState({
                        condition: 'PDVersions',
                        data: newProcessResult.result_message,
                    });
                } else {
                    throw new Error('不太可能跑到这个状态.');
                }
            })
            .catch((error) => {
                updateState({
                    condition: 'Error',
                    data: error.message,
                });
                throw new Error(error.message);
            });
    }
    function onPdvSelect(pdaid: string, userid: string, initProcessVars: InitProcessVars, ignoreWarning: boolean, ignoreAuth: boolean) {
        doNewProcessByPdaid(pdaid, userid, initProcessVars, ignoreWarning, ignoreAuth)
            .then((activeresult) => {
                if (activeresult.result_code === '1') {
                    // 成功
                    updateState({
                        condition: 'Success',
                        data: {
                            piid: activeresult.result_message.piid,
                        },
                    });
                } else if (activeresult.result_code === '2') {
                    // 没权限
                    updateState({
                        condition: 'NoAuth',
                        data: activeresult.result_message,
                    });
                } else if (activeresult.result_code === '3') {
                    // 多实例警告
                    updateState({
                        condition: 'Warning',
                        data: activeresult.result_message,
                        from: {
                            pdaid,
                        },
                    });
                } else if (activeresult.result_code === '4') {
                    // 多实例禁止
                    updateState({
                        condition: 'Forbidden',
                        data: activeresult.result_message,
                    });
                }
            })
            .catch((error) => {
                updateState({
                    condition: 'Error',
                    data: error.message,
                });
                throw new Error(error.message);
            });
    }
    function donewprocess() {
        if (state.condition === 'Warning') {
            if (state.from.pdid) {
                onPdSelect(state.from.pdid, userid, initProcessVars, true, true);
            } else if (state.from.pdaid) {
                onPdvSelect(state.from.pdaid, userid, initProcessVars, true, true);
            }
        }
    }
    function DoTask(ti) {
        //在选择任务之后，将redux中的list数据进行更新
        // getOpenTiData({
        //     piid: ti.piid,
        //     ti: ti,
        // })
        updateState({
            condition: 'Success',
            data: { piid: ti.piid, ti: ti },
        });
    }
    function doPDVTask(selectedTi) {
        //在这里触发更新pdList，在没有选择任务之前，都应该显示pdid或pdaid
        onPdvSelect(selectedTi, userid, initProcessVars, ignoreAuth, true);
    }

    if (state != null) {
        if (state.condition == 'NoAuth') {
            return (
                <Modal title={'无权限开启流程'} centered maskClosable={false} visible={true} style={{ width: '50%', height: '50%' }} footer={[]}>
                    <NoAuth message={state.data.noauth_message}></NoAuth>
                </Modal>
            );
        } else if (state.condition == 'Success') {
            return (
                <GetUserInfoContext.Provider value={{ getUserInfo: () => { return Object } }}>
                    <PIViewer piid={state.data.piid} onDestory={onDestory} onTiChanged={onTiChanged}></PIViewer>;
                </GetUserInfoContext.Provider>
            )
        } else if (state.condition == 'Warning') {
            return (
                <Modal title="一主题多种流程警告" centered maskClosable={false} visible={true} style={{ width: '50%', height: '50%' }} footer={[]}>
                    <ActivePIList4Warning list={state.data.pids} onViewProcessDetail={(ti) => alert('查看详情：' + ti.piid)} onDoTask={(ti) => DoTask(ti)} onDoNewProcess={donewprocess}></ActivePIList4Warning>
                </Modal>
            );
        } else if (state.condition == 'Forbidden') {
            return (
                <Modal title="一主题多流程禁止" getContainer={false} centered maskClosable={false} visible={true} style={{ width: '50%', height: '50%' }} footer={[]}>
                    <ActivePIList4Forbidden list={state.data.pids} onViewProcessDetail={(ti) => alert('查看详情：' + ti.piid)} onDoTask={(ti) => DoTask(ti)}></ActivePIList4Forbidden>
                </Modal>
            );
        } else if (state.condition == 'PDVersions') {
            return (
                <Modal title={'多版本流程'} getContainer={false} centered maskClosable={false} visible={true} style={{ width: '50%', height: '50%' }} footer={[]}>
                    <PDVList list={state.data.pdvlist} onSelect={(selectedTi) => doPDVTask(selectedTi)}></PDVList>
                </Modal>
            );
        } else if (state.condition == 'Error') {
            return <div>{state.data}</div>;
        } else {
            return <div>Loading...</div>;
        }
    } else {
        return null;
    }
}
